package yang.yu.sunny.service.impl;

import yang.yu.sunny.domain.product.ProductCategory;
import yang.yu.sunny.domain.sales.Order;
import yang.yu.sunny.domain.sales.OrderItem;
import yang.yu.sunny.infra.elasticsearch.ProductCategorySearcher;
import yang.yu.sunny.infra.elasticsearch.ProductSearcher;
import yang.yu.sunny.infra.persistence.sales.OrderItemMapper;
import yang.yu.sunny.infra.persistence.sales.OrderMapper;
import yang.yu.sunny.service.OrderDto;
import yang.yu.sunny.service.OrderItemDto;
import yang.yu.sunny.service.OrderService;

import javax.inject.Inject;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * Created by yyang on 16/4/11.
 */
public class OrderServiceImpl implements OrderService {

    @Inject
    private OrderMapper orderMapper;

    @Inject
    private OrderItemMapper orderItemMapper;

    @Inject
    ProductCategorySearcher categorySearcher;

    @Inject
    ProductSearcher productSearcher;


    @Override
    public OrderDto getOrder(Long id) {

        Order order = orderMapper.get(id);
        //return new OrderAssembler().toDto(order);
        return null;
    }

    @Override
    public List<OrderItemDto> findOrderItems(String categoryNameFragment, String productSn) {

        //从ElasticSearch根据类别名称获得匹配的类别ID的列表
        List<Long> categoryIds = categorySearcher.findByName(categoryNameFragment)
                .stream().map(ProductCategory::getId).collect(toList());

        //在order_items中进行无关联的单表查询,返回订单项目列表
        List<OrderItem> items = orderItemMapper.findByCategoryAndProductSn(categoryIds, productSn);

        //将订单项目OrderItem对象转换成订单项目视图OrderItemDto对象,后者包含产品名称等OrderItem中没有的属性
        return new OrderItemAssembler(categorySearcher, productSearcher).toDto(items);
    }
}
